package com.goktech.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.goktech.pojo.Commodity;
import com.goktech.mapper.CommodityMapper;
import com.goktech.service.CommodityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goktech.utils.CacheClient;
import com.goktech.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.goktech.utils.Constants.*;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 初茶
 * @since 2023-05-14
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements CommodityService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<List<Commodity>> succulentList() {
        String redisCache = stringRedisTemplate.opsForValue().get(COMMODITY_KEY);
        if (redisCache != null) {
            return Result.ok(JSONUtil.toList(redisCache, Commodity.class));
        }
        List<Commodity> commodityList = baseMapper.selectList(Wrappers.lambdaQuery(Commodity.class).eq(Commodity::getCgId, 1));
        CacheClient cacheClient = new CacheClient(stringRedisTemplate);
        cacheClient.set(COMMODITY_KEY, commodityList, COMMODITY_TTL, TimeUnit.MINUTES);
        return Result.ok(commodityList);
    }

    @Override
    public Result<List<Commodity>> artificialList() {
        String redisCache = stringRedisTemplate.opsForValue().get(ARTIFICIAL_KEY);
        if (redisCache != null) {
            return Result.ok(JSONUtil.toList(redisCache, Commodity.class));
        }
        List<Commodity> commodityList = baseMapper.selectList(Wrappers.lambdaQuery(Commodity.class).eq(Commodity::getCgId, 2));
        CacheClient cacheClient = new CacheClient(stringRedisTemplate);
        cacheClient.set(ARTIFICIAL_KEY, commodityList, COMMODITY_TTL, TimeUnit.MINUTES);
        return Result.ok(commodityList);
    }

    @Override
    public Result<Commodity> goodsDetail(Integer id) {
        return Result.ok(baseMapper.selectOne(Wrappers.lambdaQuery(Commodity.class).eq(Commodity::getCmId, id)));
    }
}
